#include "stdafx.h"
#include "isapi_python.h"
#include "HttpContext.h"

#define LOCAL_BUFFER_SIZE 1024

using namespace std;

void HttpRequest::EnsureBuffer() {
	size_t actualLocalBufferSize = LocalRequestBuffer.size();

	if(LOCAL_BUFFER_SIZE > actualLocalBufferSize) {
		vector<BYTE> requestBytes = Context->GetRequestBytes(LOCAL_BUFFER_SIZE - actualLocalBufferSize);

		for(size_t counter = 0; counter < requestBytes.size(); counter++) {
			LocalRequestBuffer.push(requestBytes[counter]);
		}
	}
}

string HttpRequest::Read(const DWORD length) {
	DWORD bytesRead = 0;
	string output("", length);
	
	EnsureBuffer();
	while (bytesRead < length && LocalRequestBuffer.size() > 0) {
		
		//Spin through the buffer and take what you need.
		while(bytesRead < length && LocalRequestBuffer.size() > 0) {
			output[bytesRead] = LocalRequestBuffer.front();
			LocalRequestBuffer.pop();
		
			bytesRead++;
		}

		EnsureBuffer();
	}

	if(bytesRead < length) {
		output.resize(bytesRead);
	}

	return output;
}

string HttpRequest::ReadLine() {
	string outputValue = "";

	EnsureBuffer();
	while(LocalRequestBuffer.size() > 0 && (LocalRequestBuffer.front() != '\r' && LocalRequestBuffer.front() != '\n')){
		
		//Spin through looking for carriage returns or linefeeds.
		while(LocalRequestBuffer.size() > 0 && (LocalRequestBuffer.front() != '\r' && LocalRequestBuffer.front() != '\n')) {
			outputValue.append((LPCSTR)&LocalRequestBuffer.front(), 1);
			LocalRequestBuffer.pop();
		}

		EnsureBuffer();
	}

	//Burn off any line termination chars.
	if(LocalRequestBuffer.front() == '\r') {
		LocalRequestBuffer.pop();
	}

	if(LocalRequestBuffer.front() == '\n') {
		LocalRequestBuffer.pop();
	}
	
	return outputValue;
}